//
//  MyStandingsViewController.m
//  EasyToTesco2.0
//
//  Created by 袖手旁觀 on 16/6/21.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "MyStandingsViewController.h"

#import "integModel.h"
#import "TopStatusView.h"
#import "RechargeCell.h"

#define Margin 8

@interface MyStandingsViewController ()
<UITableViewDataSource,
UITableViewDelegate>
{
    NSUInteger   _refreshIndex;
    NSUInteger   _type;
    UIImageView *noDrawImage;
}

@property (nonatomic,strong) UITableView     *tableView;
@property (nonatomic,strong) NSMutableArray<integModel *>  *allStandingArray;
@property (nonatomic,strong) UILabel         *AllStandings;
@property(nonatomic,strong)  UILabel         * total;

@end

static NSString *const reuseIdentifier = @"reuseIdentifier";


@implementation MyStandingsViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self loadIntegData];
    [self showLoadingView];
    
    self.tableView.mj_footer = [TopPullRefreshAnaimation footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    _refreshIndex = 1;
    _type = 0;
    
    
    UIButton *type = [UIButton buttonWithType:UIButtonTypeCustom];
    type.frame = CGRectMake(0,0,50,30);
    [type setImage:[UIImage imageNamed:@"home_location_down"] forState:UIControlStateNormal];
    [type setImage:[UIImage imageNamed:@"home_location_down"] forState:UIControlStateHighlighted];
    [type setTitle:@"类型" forState:UIControlStateNormal];
    type.titleLabel.font = FONT(15);
    type.imageEdgeInsets = UIEdgeInsetsMake(0,48,0,-10);
    [[type rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        [self typeClick];
    }];
    [type setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:type];
    self.navigationItem.rightBarButtonItem= item;

}

#pragma mark 选择类型
- (void)typeClick
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"cancle");
    }];
    
    UIAlertAction *allAction = [UIAlertAction actionWithTitle:@"所有类型" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        _type = 0;
        [self resetStatus];
    }];
    [allAction setValue:DEFAULT_COLOR forKey:@"titleTextColor"];
    
    
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"每日赠送" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _type = 1;
         [self resetStatus];
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"官方让利金赠送" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _type = 2;
         [self resetStatus];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"推广会员奖励" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        _type = 3;
        [self resetStatus];
    }];


    [alert addAction:cancleAction];
    [alert addAction:allAction];
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    [self presentViewController:alert animated:true completion:nil];
}


//重置数据
- (void)resetStatus
{
    _refreshIndex = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self.allStandingArray removeAllObjects];
    [self loadIntegData];
}


#pragma mark 数据请求
- (void)loadMoreData
{
    _refreshIndex ++;
    [self loadIntegData];
    [_tableView.mj_footer endRefreshing];
}

- (void)loadIntegData
{
    NSString *refreshIndexStr = [NSString stringWithFormat:@"%zd",_refreshIndex];
    NSString *type = [NSString stringWithFormat:@"%zd",_type];
    NSDictionary *params = @{@"username":USERNAME,@"p":refreshIndexStr,@"score_type":type};
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/User/newInteg" completeBlock:^(id object) {
        
        if (JudgeBackDataCode) {
            
            NSDictionary *data = [object objectForKey:@"data"];
            NSMutableArray *list = [integModel arrayOfModelsFromDictionaries:[data objectForKey:@"list"] error:nil];
            [self.allStandingArray addObjectsFromArray:list];;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self buildView];
                
                NSString *str = nil;
                if (JudgeInvididualOrSeller) {
                    str = [NSString stringWithFormat:@"已赠送代金券%@",[data objectForKey:@"total"]];
                }else{
                    str = [NSString stringWithFormat:@"已赠送让利金%@",[data objectForKey:@"total"]];
                }
                self.total.text = str;
            });
            
        }else{
            
            if (_refreshIndex == 1) {
                
                NSString *str = nil;
                if (JudgeInvididualOrSeller) {
                    str = @"已赠送代金券0.0";
                }else{
                    str = @"已赠送让利金0.0";
                }
                self.total.text = str;
                
                noDrawImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_NoRecord"]];
                [self.view addSubview:noDrawImage];
                
                [noDrawImage mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.centerX.equalTo(self.view.mas_centerX);
                    make.centerY.equalTo(self.view.mas_centerY).offset(-HEIGHT/8);
                    make.width.mas_equalTo(WIDTH/1.5);
                    make.height.mas_equalTo(WIDTH/2.4);
                }];
                
                [self.tableView removeFromSuperview];
                
            }else{
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }
        [self.tableView reloadData];
    }];
    
    [self hideLoadingView];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.allStandingArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    RechargeCell *cell=[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    
    if (cell==nil) {
        cell=[[RechargeCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reuseIdentifier];
        
    }
    cell.selectionStyle =UITableViewCellSelectionStyleNone;
    integModel *model = self.allStandingArray[indexPath.row];
    
    //奖励让利金
    cell.UserLabel.text = [NSString stringWithFormat:@"+%@",model.operator_score];
    
    //总让利金
    cell.moneyLabel.text= model.after_score;
    
    //类型
    NSString *str = nil;
    if ([model.type isEqualToString:@"0"]) {
        str = @"每日赠送";
    }else if ([model.type isEqualToString:@"5"]){
        str = @"推广会员奖励";
    }else if ([model.type isEqualToString:@"7"]){
        
        if (JudgeInvididualOrSeller) {
            str = @"官方代金券赠送";
        }else{
            str = @"官方让利金赠送";
        }
        
    }else if ([model.type isEqualToString:@"8"]){
        str = @"推广会员奖励";
    }else{
        str = @"推广会员奖励";
    }
    cell.timeLabel.text = str;
    cell.timeLabel.numberOfLines = 0;
    cell.timeLabel.font = FONT(12);
    cell.timeLabel.textAlignment = NSTextAlignmentCenter;
    
    //时间
    cell.statusLabel.text = model.create_time;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 3;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}



#pragma mark UI
- (void)buildView
{
    NSArray *arr = @[@"奖励金额",@"总让利金",@"类型",@"时间"];
    if (JudgeInvididualOrSeller) {
       arr =  @[@"奖励金额",@"总代金券",@"类型",@"时间"];
    }
    TopStatusView *topStatusView = [[TopStatusView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 50) titleArray:arr];
    [self.view addSubview:topStatusView];
    
    [self.view addSubview:self.tableView];
    
    self.total = [[UILabel alloc] initWithFrame:CGRectMake(0,HEIGHT-50-64,WIDTH,45)];
    [self.view addSubview:self.total];
    _total.textColor = DEFAULT_COLOR;
    _total.backgroundColor = [UIColor whiteColor];
    _total.font = BOLDFONT(15);
    _total.text = @"已赠送";
    _total.textAlignment = NSTextAlignmentCenter;
    _total.layer.borderColor = [UIColor grayColor].CGColor;
    _total.layer.borderWidth = 0.2f;
}

- (NSNumber *)formatValue:(CGFloat)value {
    
    return  @([NSString stringWithFormat:@"%.4f", value].floatValue);
}

- (NSMutableArray <integModel *> *)allStandingArray {
    if (!_allStandingArray) {
        _allStandingArray = [NSMutableArray array];
    }
    return _allStandingArray;
}

- (UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,50,WIDTH, HEIGHT-50-64-45) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = BACKGROUND_COLOR;
        _tableView.rowHeight = 50;
        [_tableView registerNib:[UINib nibWithNibName:@"RechargeCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:reuseIdentifier];
    }
    return _tableView;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
}


@end
